<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{path:'/home'}">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item :to="{path:'/goods'}">商品列表</el-breadcrumb-item>
            <el-breadcrumb-item>编辑商品</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图 -->
        <el-card>
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="120px">
            <el-tabs tab-position="left" v-model="activeStep">
                <el-tab-pane label="基本信息" name="0">
                    <el-form-item label="商品名称" prop="goods_name">
                        <el-input v-model="editForm.goods_name"></el-input>
                    </el-form-item>
                    <el-form-item label="商品价格" prop="goods_price">
                        <el-input-number :min="0" v-model="editForm.goods_price"></el-input-number>
                    </el-form-item>
                    <el-form-item label="商品重量" prop="goods_weight">
                        <el-input-number :min="0" v-model="editForm.goods_weight"></el-input-number>
                    </el-form-item>
                    <el-form-item label="商品数量" prop="goods_number">
                        <el-input-number :min="1" v-model="editForm.goods_number"></el-input-number>
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="商品参数" name="1">
                    <el-form-item :label="item.attr_name" v-for="item in attrList" :key="item.attr_id">
                        <el-checkbox-group v-model="item.checked_vals">
                            <el-checkbox border v-for="(val,index) in item.attr_vals" :key="index" :label="val"></el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="商品属性" name="2">
                    <el-form-item :label="item.attr_name" v-for="item in attrList2" :key="item.attr_id">
                        <el-input v-model="item.attr_vals"></el-input>
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="商品图片" name="3">
                    <!-- 图片上传 -->
                    <el-upload
                        class="upload-demo"
                        :file-list="picList"
                        :action="uploadUrl"
                        :headers="headerObject"
                        :on-success="handleSuccess"
                        :on-preview="handlePreview"
                        :on-remove="handleRemove"
                        list-type="picture">
                        <el-button size="small" type="primary">点击上传</el-button>
                        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
                    </el-upload>
                </el-tab-pane>
                <el-tab-pane label="商品内容" name="4">
                    <quill-editor v-model="editForm.goods_introduce"
                        :options="quillEditorOption"
                    ></quill-editor>
                    <div style="margin-top:16px;">
                        <el-button type="primary" @click="edit">保存商品</el-button>
                    </div>
                </el-tab-pane>
            </el-tabs>
            </el-form>
        </el-card>
        <el-dialog :visible.sync="previewOn" title="预览">
            <img :src="previewUrl" style="width:100%;">
        </el-dialog>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                uploadUrl: process.env.VUE_APP_API+'upload',
                headerObject: {
                    Authorization: window.sessionStorage.getItem('token')
                },
                activeStep: '0',
                currentGoodsId: this.$route.params.id,
                attrList: [],
                attrList2: [],
                picList: [],
                previewOn: false,
                previewUrl: '',
                editForm: {
                    goods_name: '',
                    goods_price: 0,
                    goods_weight: 0,
                    goods_number: 1,
                    goods_introduce: '',
                    pics: [],
                    attrs: []
                },
                selectedCatIds: [],
                selectedAttrs: [],
                editFormRules: {
                    goods_name: [
                        { required:true ,trigger: 'blur', message: '请输入名称'},
                        { max: 256 ,trigger: 'blur', message: '最长256字符'},
                    ],
                    goods_price: { required:true ,trigger: 'blur', message: '请输入价格'},
                    goods_weight: { required:true ,trigger: 'blur', message: '请输入重量'},
                    goods_number: { required:true ,trigger: 'blur', message: '请输入数量'}
                },
                quillEditorOption: {
                    theme: 'snow',
                    placeholder: '请输入商品描述信息',
                }
            }
        },
        created() {
            //this.currentGoodsId=this.$route.params.goods_id;
            this.getGoods();
        },
        methods: {
            async getGoods() {
                const {data:res} = await this.$http.get('goods/'+this.$route.params.id);
                if(res.meta.status!=200) {
                    return this.$message.error('获取商品信息失败！'+res.meta.msg);
                }
                console.log("goods",res.data);
                this.editForm.goods_name=res.data.goods_name;
                this.editForm.goods_price=res.data.goods_price;
                this.editForm.goods_weight=res.data.goods_weight;
                this.editForm.goods_number=res.data.goods_number;
                this.editForm.goods_introduce=res.data.goods_introduce;
                //处理类别
                this.editForm.goods_cat=res.data.goods_cat;
                this.selectedCatIds=res.data.goods_cat?res.data.goods_cat.split(','):[];
                // 处理图片列表
                this.editForm.pics=res.data.pics;
                this.picList=[];
                res.data.pics.forEach(pic=>{
                    this.picList.push({
                        id: pic.pics_id,
                        name: pic.pics_big,
                        url: pic.pics_big_url
                    });
                });
                this.editForm.attrs=res.data.attrs;
                //启动属性获取
                this.getAttrList('many');
                this.getAttrList('only');
            },
            async getAttrList(sel) {
                if(this.selectedCatId)
                {
                    const { data: res} = await this.$http.get('categories/'+this.selectedCatId+'/attributes',
                        {params: {sel: sel}});
                    if(res.meta.status!=200) {
                        return this.$message.error('获取分类参数失败！'+res.meta.msg);
                    }                   
                    console.log('getAttrList',sel,res.data);
                    if(sel==='many') {
                        this.attrList=res.data;
                        this.attrList.forEach(attr=>{
                            if(attr.attr_vals)
                            {
                                attr.attr_vals=attr.attr_vals.split(',');
                                //根据editForm.attrs标记是否
                                this.$set(attr,'checked_vals', this.findAttr(attr.attr_id,'many'));
                            }                          
                            else
                            {
                                attr.attr_vals=[];
                                // attr.checked_vals=[];
                                this.$set(attr,'checked_vals', []);
                            }
                        });
                    }
                    else {
                        this.attrList2=res.data;
                        this.attrList2.forEach(attr=>{
                            //根据editForm.attrs标记是否
                            attr.attr_vals = this.findAttr(attr.attr_id,'only')
                        });
                    }
                }
            },
            findAttr(attr_id,attr_sel) {
                if(attr_sel==='many') { 
                    var vals=[]; 
                    const  idx = this.editForm.attrs.forEach(attr=>{
                        if(attr.attr_id===attr_id) vals.push(attr.attr_value);
                    });
                    return vals;
                } else {
                    const idx = this.editForm.attrs.findIndex(attr=>attr.attr_id===attr_id);
                    return idx!=-1?this.editForm.attrs[idx].attr_value:'';
                }
                
            },
            handleSuccess(res) {
                console.log('upload over',res);
                this.picList.push({
                    name: res.data.tmp_path,
                    url: res.data.url
                });
                //this.editForm.pics.push({pic: res.data.tmp_path});
            },
            handlePreview(file) {
                console.log('handlePreview',file);
                this.previewUrl=file.url;
                this.previewOn=true;
            },
            handleRemove(file) {
                console.log('handleRemove',file);
                var url=file.url;
                var idx=this.picList.findIndex(pic=>pic.url===url);
                if(idx!=-1) this.picList.splice(idx,1);
            },
            edit() {
                this.$refs.editFormRef.validate(async (valid,err)=> {
                    if(!valid) {
                        console.log('valid',err);
                        return this.$message.error('请先填写必要的表单项！'); 
                    }
                    // 处理图片 从picList到pics
                    this.editForm.pics=[];
                    this.picList.forEach(pic=>{
                        if(pic.id) {
                            // 已有图片保留
                             this.editForm.pics.push({  
                                 pics_id: pic.id
                             })
                        }
                        else {
                            // 新图片，提交创建
                            this.editForm.pics.push({
                                 pic: pic.name
                             })
                        }
                    });        
                    this.editForm.attrs=[];
                    //动态attr
                    this.attrList.forEach(attr => {
                        attr.checked_vals.forEach(val=>{
                            if(val)
                            this.editForm.attrs.push({
                                attr_id: attr.attr_id,
                                attr_value: val
                            });
                        });
                    });
                    //静态attr
                    this.attrList2.forEach(attr => {
                        if(attr.attr_vals)
                            this.editForm.attrs.push({
                                attr_id: attr.attr_id,
                                attr_value: attr.attr_vals
                            });
                    });
                   
                    console.log('editForm',this.editForm);
                    const {data:res} = await this.$http.put('goods/'+this.$route.params.id
                        ,this.editForm);
                     if(res.meta.status!=200) {
                        return this.$message.error('编辑商品失败！'+res.meta.msg);
                    }
                    this.$message.success('编辑商品成功！');
                    this.$router.push('/goods')
                });
            }
        },
        computed: {
            selectedCatId() {
                if(this.selectedCatIds&&this.selectedCatIds.length>0)
                    return this.selectedCatIds[this.selectedCatIds.length-1];
            }
        }
    }
</script>

<style lang="less" scoped>
.el-checkbox {
    margin: 0 10px 0 0 !important;
}
</style>